--[[
    author:Lee
    time:2021-10-18 11:35:33
]]
local require = require;
local loadstring = loadstring;
local ngx     = ngx;
local type = type;
local tostring = tostring;
local table =table;
local tonumber = tonumber;
local assert= assert;
local setmetatable= setmetatable;

local ns_env    = require( "modules.env.env" );
local uu         = require("modules.commhm.utils");
local log        = require("modules.commhm.log");

local ns_aes = require("resty.aes")
local ns_resty_str = require("resty.string")
local cjson = require("cjson.safe")

local FOO = {
	_VERSION = '0.12.1',
};


--aes默认加密配置
local business_aes = {
  key = "d1438d2d2d9ad7b7",    --business_lihu_20211018
  hash= {iv="26cd7cb1bc926717"},     --business_lihu@mini1.cn
}

if ns_env.debug == 1 then
    business_aes.key = "d1438d2d2d9ad7b0"
    business_aes.hash= {iv="26cd7cb1bc926710"}
end

local _M = {
    _VERSION = "0.12.1"
}
local mt = {__index = _M}


function _M.new(self,key,hash_iv)
    local param_list = {
        cbc_128_vi_obj = assert(ns_aes:new(key or business_aes.key, nil, ns_aes.cipher(128, "cbc"), hash_iv or business_aes.hash))
    }
    return setmetatable(param_list, mt)
end


--aes解密内容
function _M.decrypt(self,str)
    str = ngx.decode_base64(str)
    log.debug("business_common aes decrypt begin str=" .. str)
    local data = self.cbc_128_vi_obj:decrypt(str) --返回json数据
    local t = cjson.decode(data)
    log.debug("business_common aes decrypt end  t=" .. uu.to_str(t))
    if not t then
        log.day_list("business_common", "aes", "aes decrypt body failed")
        return nil
    end
    return t
end

--aes加密接口
function _M.encrypt(self,str)
    if type(str) == "table" then
        str = uu.table2json(str)
    end
    log.debug("business_common aes encrypt begin str=" .. str)
    local data = self.cbc_128_vi_obj:encrypt(str)
    log.debug("business_common aes encrypt end data=" .. ngx.encode_base64(data))
    return ngx.encode_base64(data)
end


return _M

